/*
*新增复合基准
*AddBenchmark.js*/

import React, {Component,PureComponent} from 'react';
import { Modal, Button,Form, Row,Col,Input, Select, Icon,message,Radio} from 'antd';
import { connect } from 'react-redux';
import style from './addBenchmark.less';
const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
class CompoundDatum extends React.Component {
  constructor(props) {
    super(props);
    console.log(887766,this.props,props)
    const value = props.benchmarkValue||{} ;
    this.state = {
      benchmarkRate: value.benchmarkRate,
      benchmarkCode: value.benchmarkCode,
    };
  }

  handleNumberChange = (e) => {
    const benchmarkRate = parseInt(e.target.value || 0, 10);
    console.log(11233,benchmarkRate)
    if (isNaN(benchmarkRate)) {
      return;
    }
    this.setState({ benchmarkRate });
    this.props.dispatch({
      type:`benchmarkMgt/setState`,
      payload:{
        'benchmarkRate':e.target.value,
      }
    })
    this.triggerChange({ benchmarkRate });
  }

  handleCurrencyChange = (benchmarkCode) => {
    console.log(232323,benchmarkCode)

    this.setState({ benchmarkCode });
    this.props.dispatch({
      type:`benchmarkMgt/setState`,
      payload:{
        'benchmarkCode':benchmarkCode,
      }
    })
    this.triggerChange({ benchmarkCode });
  }
  
  triggerChange = (changedValue) => {
    const onChange = this.props.onChange;
    if (onChange) {
      onChange(Object.assign({}, this.state, changedValue));
    }

    console.log(44556677,changedValue,this.props,this.state)
  }
  
  render() {
    const {benchmarksList} = this.props;
    console.log(4322,this.props)

    const state = this.state;
    return (
      <Row type="flex" justify="start">
        <Col span={7}>
          <Input
            type="text"
            value={state.benchmarkRate}
            onChange={this.handleNumberChange}
            addonAfter="%"
            style={{width:100}}
          />
        </Col>
        <Col span={10}>
          <Select
            value={state.benchmarkCode}
            onChange={this.handleCurrencyChange}
            allowClear={true}
            placeholder="请选择基准"
            style={{width:150}}
          >
            {
              benchmarksList.map((item,i)=><Option value={`${item.benchCode}`} key={i}>{item.benchCode}-{item.benchName}</Option>)
            }
          </Select>
        </Col>
      </Row>
    );
  }
}

let uuid = 0;
const AddBenchmarkForm = Form.create()(
  class extends React.Component {
    baseRatechange=(e)=>{
      const baseRate = parseInt(e.target.value || 0, 10);
      console.log(11233,baseRate)
      if (isNaN(baseRate)) {
        return;
      }
      data.dispatch({
        type:`benchmarkMgt/setState`,
        payload:{
          'baseRate':baseRate,
        }
      })
    }
    remove = (k) => {
      const { form } = this.props;
      const keys = form.getFieldValue('keys');
      if (keys.length === 0) {
        return;
      }
      form.setFieldsValue({
        keys: keys.filter(key => key !== k),
      });
    }

    add = () => {
      const { form } = this.props;
      const keys = form.getFieldValue('keys');
      const nextKeys = keys.concat(uuid);
      console.log(56722111,keys,nextKeys)
      if(nextKeys.length < 4){
        uuid++;
        form.setFieldsValue({
          keys: nextKeys,
        });
      }else{
        message.warning('复合基准最多4个')
      }
      
    }
    render() {
      const { visible, onCancel, onCreate, form ,data} = this.props;
      console.log(34500,data)
      const { getFieldDecorator, getFieldValue } = this.props.form;
      
      getFieldDecorator('keys', { initialValue: [] });
      const keys = getFieldValue('keys');
      const formItems = keys.map((k, index) => {
        return (
          <FormItem
            required={false}
            key={k}
          >
            {getFieldDecorator(`jizhuns[${k}]`, {
              rules: [{
                required: true,
                message: "请选择基准或输入权重",
              }],
            })(
              <CompoundDatum {...data}/>
            )}
            {keys.length > 0 ? (
              <Icon
                className="dynamic-delete-button"
                type="minus-circle-o"
                onClick={() => this.remove(k)}
              />
            ) : null}
          </FormItem>
        );
      });
      return (
        visible ?
        <Modal
          visible={visible}
          title="新增"
          okText="提交"
          cancelText="取消"
          onCancel={onCancel}
          onOk={onCreate}
        >
          <Form layout="vertical" className={style.benchStyle}>
            <FormItem
              label="基准"
            >
              {getFieldDecorator(`jizhun`, {
                rules: [{
                  required: true,
                  message: "请选择基准或输入权重",
                }],
              })(
                <CompoundDatum {...data}/>
              )}
              {(
                <Icon
                  className="dynamic-delete-button"
                  type="plus-circle-o"
                  onClick={this.add}
                />
              )}
            </FormItem>
            {formItems}
            <FormItem
              label="绝对收益"
            >
              {getFieldDecorator(`baseRate`, {
                initialValue: data.baseRate,
                rules: [
                  { whitespace: true,required: true, pattern:/^([1-9]\d*|[0]{1,1})$/, message: '请输入整数!' },
                ],
                initialValue: 0,
              })(
                <Input
                  addonAfter="%"
                  style={{width:100}}
                />
              )}
            </FormItem>
            <FormItem
              label="复合基准名称"
            >
              {getFieldDecorator(`benchName`, {
                rules: [{
                  required: true,
                  message: "请输入复合基准名称",
                }],
              })(
                <Input
                  style={{width:260}}
                />
              )}
            </FormItem>
            <FormItem
              label="个人&公用标签"
            >
              {getFieldDecorator('isShare',{
                rules: [{
                  required: true,
                  message: "请选择是否公开",
                }],
                initialValue:'1' ,
              })(
                <RadioGroup>
                  <Radio value="0">个人标签</Radio>
                  <Radio value="1">公用标签</Radio>
                </RadioGroup>
              )}
            </FormItem>
            <FormItem
              label="描述"
            >
              {getFieldDecorator(`description`, {
                rules: [{
                  message: "请输入描述",
                }],
              })(
                <Input
                  style={{width:260}}
                />
              )}
            </FormItem>
          </Form>
        </Modal>:null
      );
    }
  }
);
let weight;
class AddBenchmark extends React.Component {
  state = {
    visible: false,
  };

  showModal = () => {
    this.setState({ visible: true });
  }

  handleCancel = () => {
    const form = this.formRef.props.form;
    this.setState({ visible: false });
    form.resetFields();
  }

  handleCreate = () => {
    const form = this.formRef.props.form;
    form.validateFields((err, values) => {
      if (err) {
        return;
      }
      console.log(33333,this.props)
      console.log('Received values of form: 1111', values);
      
      if(!values.jizhuns){
        message.warning('复合基准至少为2个最多4个');
        this.setState({ visible: true });
      }else if(values.jizhuns){
        values.jizhuns.push(values.jizhun);
        for(var i = 0 ;i<values.jizhuns.length;i++) {
          if(values.jizhuns[i] == "" || typeof(values.jizhuns[i]) == "undefined"){
            values.jizhuns.splice(i,1);
            i= i-1;
          }
        }
        for(let i=0;i<values.jizhuns.length;i++){
          if(values.jizhuns[i].benchmarkRate == NaN || 
            values.jizhuns[i].benchmarkRate == undefined){
            message.warning('请输入权重');
            this.setState({ visible: true });
            return;
          }else if(values.jizhuns[i].benchmarkCode == undefined){
            message.warning('请选择基准');
            this.setState({ visible: true });
            return;
          }else if(values.jizhuns[i].benchmarkRate !== NaN && values.jizhuns[i].benchmarkRate !== undefined&&
            values.jizhuns[i].benchmarkCode !== undefined){
            for(let j=i+1;j<values.jizhuns.length;j++){
              if(values.jizhuns[i].benchmarkCode == values.jizhuns[j].benchmarkCode){
                message.warning('存在相同基准,请选择不同基准');
                return;
                this.setState({ visible: true });
              }else{
                weight = values.jizhuns;
              }
            }
            
          }
        }
      }
      
      if(!_.isEmpty(weight)){
        weight.map((item)=>{
          const a =item.benchmarkRate / 100;
          item.benchmarkRate = a
        })
        const querys = {};
        querys.weight = weight;
        querys.isShare = values.isShare;
        querys.benchName = values.benchName;
        querys.baseRate = values.baseRate / 100;
        values.description&&(querys.description = values.description);
        this.props.dispatch({
          type:`benchmarkMgt/addBenchmark`,
          payload:{
            ...querys
          }
        })
        this.setState({ visible: false });
        form.resetFields();
      }
        
    });
  }

  saveFormRef = (formRef) => {
    this.formRef = formRef;
  }
  render() {
    return (
      <div>
        <Button type="primary" onClick={this.showModal}>新增</Button>
        <AddBenchmarkForm
          wrappedComponentRef={this.saveFormRef}
          visible={this.state.visible}
          onCancel={this.handleCancel}
          onCreate={this.handleCreate}
          data={this.props}
        />
      </div>
    );
  }
}
AddBenchmark.defaultProps={

}
export default connect()(AddBenchmark)